package com.bryantkobe.myspringcode.handler;

import com.bryantkobe.myspringcode.exception.BusinessException;
import com.bryantkobe.myspringcode.exception.ErrorResult;
import com.bryantkobe.myspringcode.service.MExceptionMetricsService;
import jakarta.annotation.Resource;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.context.request.NativeWebRequest;

/**
 * @description: 增强异常处理器
 * @author: alienwarezzl
 * @date: 2025/9/23
 */
@Component
@RestControllerAdvice
public class MetricAwareExceptionHandler extends GlobalExceptionHandler{

    @Resource
    private MExceptionMetricsService exceptionMetricsService;

    @Override
    public ResponseEntity<ErrorResult> handleBusinessException(BusinessException e, NativeWebRequest request) {
        // 使用虚拟线程处理监控日志，避免阻塞
        Thread.startVirtualThread(() ->
                exceptionMetricsService.recordException("business", e.getErrorCode()));

        return super.handleBusinessException(e, request);
    }

    @Override
    public ResponseEntity<ErrorResult> handleAssertionError(AssertionError e, NativeWebRequest request) {// 使用虚拟线程处理监控日志，避免阻塞
        Thread.startVirtualThread(() ->
                exceptionMetricsService.recordException("assertError", e.getMessage()));

        return super.handleAssertionError(e, request);
    }

    @Override
    public ErrorResult handleGenericException(Exception e, NativeWebRequest request) {
        // 使用虚拟线程处理监控日志，避免阻塞
        Thread.startVirtualThread(() ->
                exceptionMetricsService.recordException("exception", e.getMessage()));
        return super.handleGenericException(e, request);
    }
}
